package com.xiaobo.sql.component.query;

import com.xiaobo.sql.base.Table;
import com.xiaobo.sql.utils.SqlUtils;

import java.util.List;
import java.util.Objects;

/**
 * 查询表达式
 * @author duxiaobo
 * @date 2021/11/252:24 下午
 */
public class QueryExpression implements Table {
    private String expression;
    private List<String> contexts;
    private String aliasName;

    public QueryExpression() {
    }

    public QueryExpression(String expression, List<String> contexts) {
        this.expression = expression;
        this.contexts = contexts;
    }

    public String getExpression() {
        return expression;
    }

    public QueryExpression setExpression(String expression) {
        this.expression = expression;
        return this;
    }

    public List<String> getContexts() {
        return contexts;
    }

    public QueryExpression setContexts(List<String> contexts) {
        this.contexts = contexts;
        return this;
    }

    public String getAliasName() {
        return aliasName;
    }

    public QueryExpression as(String aliasName) {
        this.aliasName = aliasName;
        return this;
    }

    @Override
    public String toSqlAsValue() {
        StringBuilder sql = new StringBuilder();
        sql.append("(");
        toSql(sql);
        sql.append(")");
        return sql.toString();
    }

    @Override
    public void toSql(StringBuilder sql) {
        if (Objects.isNull(this.expression)) {
            return;
        }
        if (Objects.nonNull(this.contexts) && !contexts.isEmpty()) {
            for (int i = 0; i < contexts.size(); i++) {
                expression = expression.replace("${" + i + "}", contexts.get(i));
            }
        }
        sql.append(expression);
    }

    @Override
    public String toSqlToValueWithAS() {
        StringBuilder sql = new StringBuilder();
        sql.append(toSqlAsValue());
        if (Objects.nonNull(this.aliasName)) {
            sql.append(" AS ");
            SqlUtils.appendSymbol(this.aliasName, sql);
        }
        return sql.toString();
    }

    @Override
    public String toString() {
        StringBuilder sql = new StringBuilder();
        toSql(sql);
        return sql.toString();
    }
}
